//
//  LZCartTableViewCell.m
//  LZCartViewController
//
//  Created by LQQ on 16/5/18.
//  Copyright © 2016年 LQQ. All rights reserved.
//  https://github.com/LQQZYY/CartDemo
//  http://blog.csdn.net/lqq200912408
//  QQ交流: 302934443

#import "LZCartTableViewCell.h"
#import "LZConfigFile.h"
//#import "LZCartModel.h"
#import "LZGoodsModel.h"
#import <IQUIView+IQKeyboardToolbar.h>


@interface LZCartTableViewCell ()
{
    LZNumberChangedBlock numberAddBlock;
    LZNumberChangedBlock numberCutBlock;
    LZCellSelectedBlock cellSelectedBlock;
    
    NSString *goodID;
    NSString *chooseID;//选择sku的id
    NSString *countMin;//商品的最小数量
    
    NSString *countMax;//商品的最大数量;如果为0 则不限制购买的数量直到小于库存量为止
    
    NSString *countNumT;//商品的库存量
   
}
//选中按钮
@property (nonatomic,retain) UIButton *selectBtn;
//显示照片
@property (nonatomic,retain) UIImageView *lzImageView;
//商品名
@property (nonatomic,retain) UILabel *nameLabel;
//尺寸
@property (nonatomic,retain) UILabel *sizeLabel;
//时间
@property (nonatomic,retain) UILabel *dateLabel;

//价格
@property (nonatomic,retain) UILabel *priceLabel;

//数量
@property (nonatomic,retain)UILabel *numberLabel;

@property (nonatomic,retain)UITextField *numberTF;




@end

@implementation LZCartTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.backgroundColor = LZColorFromRGB(245, 246, 248);
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        [self setupMainView];
    }
    return self;
}
#pragma mark - public method
- (void)reloadDataWithModel:(LZGoodsModel*)model {
    
    [self.lzImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",model.image] ] placeholderImage:[UIImage imageNamed:@"quetu"]];
    self.nameLabel.text = model.goodsName;
    
    goodID = model.goodsID;
    chooseID = model.choseId;
    //价格
    self.priceLabel.text = [NSString stringWithFormat:@"¥%@",model.price];
    
    //规格
    if (model.guiGeArray != nil && ![model.guiGeArray isKindOfClass:[NSNull class]] && model.guiGeArray.count != 0)
    {
        
    
        NSMutableArray *array = [NSMutableArray array];
        for (int i = 0; i < model.guiGeArray.count; i++) {
            NSString *str1;
            if ([model.guiGeArray[i][@"type"] intValue] == 2) {
                str1 = model.guiGeArray[i][@"note"];
            }else {
                 str1 = model.guiGeArray[i][@"value"];
            }
          
            [array addObject:str1];
        }
        
        NSArray *tempAray = [NSArray arrayWithArray:array];
        NSString *string = [tempAray componentsJoinedByString:@" "];
        self.sizeLabel.text = string;
        self.tempSeBtn.hidden = NO;
          //规格长度自适应
        CGSize size = CGSizeMake(30,30); //设置一个行高上限
        NSDictionary *attribute = @{NSFontAttributeName: self.sizeLabel.font};
        CGSize labelsize = [self.sizeLabel.text boundingRectWithSize:size options:NSStringDrawingUsesDeviceMetrics attributes:attribute context:nil].size;
        self.sizeLabel.frame = CGRectMake(CGRectGetMinX(self.nameLabel.frame),CGRectGetMaxY(self.nameLabel.frame)+5, labelsize.width + 3, labelsize.height);
        
        //选择规格按钮自适应
        self.tempSeBtn.frame = CGRectMake(CGRectGetMaxX(self.sizeLabel.frame)+5, CGRectGetMinY(self.sizeLabel.frame)-3, 20, 20);
    }else {

        self.sizeLabel.text = @"暂无更多规格";
        
        self.tempSeBtn.hidden = YES;
        //规格长度自适应
        CGSize size = CGSizeMake(30,30); //设置一个行高上限
        NSDictionary *attribute = @{NSFontAttributeName: self.sizeLabel.font};
        CGSize labelsize = [self.sizeLabel.text boundingRectWithSize:size options:NSStringDrawingUsesDeviceMetrics attributes:attribute context:nil].size;
        self.sizeLabel.frame = CGRectMake(CGRectGetMinX(self.nameLabel.frame),CGRectGetMaxY(self.nameLabel.frame)+5, labelsize.width + 3, labelsize.height);
        
        //选择规格按钮自适应
        self.tempSeBtn.frame = CGRectMake(CGRectGetMaxX(self.sizeLabel.frame)+5, CGRectGetMinY(self.sizeLabel.frame)-3, 20, 20);
        
      
    }
   
    
    //数量
    countMin = model.minimum;
    countMax = model.maximum;
    countNumT = model.store_nums;
    
    self.numberTF.text = [NSString stringWithFormat:@"%ld",(long)model.count];
    //是否被选中
    self.selectBtn.selected = model.select;
    
}

- (void)numberAddWithBlock:(LZNumberChangedBlock)block {
    numberAddBlock = block;
}

- (void)numberCutWithBlock:(LZNumberChangedBlock)block {
    numberCutBlock = block;
}

- (void)cellSelectedWithBlock:(LZCellSelectedBlock)block {
    cellSelectedBlock = block;
}
#pragma mark - 重写setter方法
- (void)setLzNumber:(NSInteger)lzNumber {
    _lzNumber = lzNumber;
    
    self.numberTF.text = [NSString stringWithFormat:@"%ld",(long)lzNumber];
}

- (void)setLzSelected:(BOOL)lzSelected {
    _lzSelected = lzSelected;
    self.selectBtn.selected = lzSelected;
}
#pragma mark - 按钮点击方法
- (void)selectBtnClick:(UIButton*)button {
    button.selected = !button.selected;
    
    if (cellSelectedBlock) {
        cellSelectedBlock(button.selected);
    }
}

#pragma mark －＝－＝－＝－＝单个商品数量的加减
- (void)addBtnClick:(UIButton*)button {

    NSInteger count = [self.numberTF.text integerValue];
    count++;
        NSDictionary *saveDic = [SaveDataMethord readLoginData];
    
        NSDictionary *parameDic = @{@"userid":saveDic[@"userid"],@"sku_id":chooseID,@"num":[NSString stringWithFormat:@"%ld",count],@"actoken":[Md5Apiway getMD5data:saveDic[@"userid"]]};
        
        [HttpRequest postWithURLString:POST(Shop_CartUpdateCartNum) parameters:parameDic success:^(id responseObject) {
            if ([responseObject[@"ret"] intValue] != 200) {
                [[DSLHUD shareDSLHUD] showTextNoActivity:@"更改此商品数量出错" timeLength:1.5];
                return ;
            }
            NSString *strT = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"code"]];
            if ([strT intValue] != 0) {
                [MBProgressHUD showText:responseObject[@"data"][@"msg"]];
         
            }else {
             
                
                if (numberAddBlock) {
                    numberAddBlock(count);
                }
            }
            
           
            NSLog(@"修改商品数量返回的结果 ＝＝＝ %@",responseObject);
        } failure:^(NSError *error) {
            
        }];
        
    

    
  
}

- (void)cutBtnClick:(UIButton*)button {
    
    NSInteger count = [self.numberTF.text integerValue];
    count--;
    if(count <= 0){
        return ;
    }

    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    
    NSDictionary *parameDic = @{@"userid":saveDic[@"userid"],@"sku_id":chooseID,@"num":[NSString stringWithFormat:@"%ld",count],@"actoken":[Md5Apiway getMD5data:saveDic[@"userid"]]};
    
    [HttpRequest postWithURLString:POST(Shop_CartUpdateCartNum) parameters:parameDic success:^(id responseObject) {
        

        if ([responseObject[@"ret"] intValue] != 200) {
            [[DSLHUD shareDSLHUD] showTextNoActivity:@"更改此商品数量出错" timeLength:1.5];
            return ;
        }
        NSString *strT = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"code"]];
        if ([strT intValue] != 0) {
            [MBProgressHUD showText:responseObject[@"data"][@"msg"]];
            
        }else {
            
            if (numberCutBlock) {
                numberCutBlock(count);
            }
        }
        
        NSLog(@"修改商品数量返回的结果 ＝＝＝ %@",responseObject);
    } failure:^(NSError *error) {
        
    }];
    
    
   
}
#pragma mark - 布局主视图
-(void)setupMainView {
    //白色背景
    UIView *bgView = [[UIView alloc]init];
    bgView.frame = CGRectMake(0, 0, LZSCREEN_WIDTH - 0, lz_CartRowHeight - 0);
    bgView.backgroundColor = [UIColor whiteColor];
  
    [self addSubview:bgView];
    
    //选中按钮
    UIButton* selectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    selectBtn.center = CGPointMake(20, bgView.height/2.0);
    selectBtn.bounds = CGRectMake(0, 0, 30, 30);
    [selectBtn setImage:[UIImage imageNamed:lz_Bottom_UnSelectButtonString] forState:UIControlStateNormal];
    [selectBtn setImage:[UIImage imageNamed:lz_Bottom_SelectButtonString] forState:UIControlStateSelected];
    [selectBtn addTarget:self action:@selector(selectBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:selectBtn];
    self.selectBtn = selectBtn;
    
    //照片背景
    UIView *imageBgView = [[UIView alloc]init];
    imageBgView.frame = CGRectMake(selectBtn.right + 5, 10, 80, 100);
    imageBgView.backgroundColor = [UIColor whiteColor];
    [bgView addSubview:imageBgView];
    
    //显示照片
    UIImageView* imageView = [[UIImageView alloc]init];
    imageView.image = [UIImage imageNamed:@"满199减25"];
    imageView.frame = CGRectMake(imageBgView.left + 5, 20, 70, 80);
    imageView.contentMode = UIViewContentModeScaleToFill;
    [bgView addSubview:imageView];
    self.lzImageView = imageView;
    
    //CGFloat width = (bgView.width - imageBgView.right - 30)/2.0;
    //商品名
    UILabel* nameLabel = [[UILabel alloc]init];
    nameLabel.frame = CGRectMake(CGRectGetMaxX(imageBgView.frame)+10, CGRectGetMinY(imageBgView.frame), bgView.width - CGRectGetMaxX(imageBgView.frame)-10, 40);
    nameLabel.numberOfLines = 2;
    nameLabel.font = [UIFont systemFontOfSize:15];
    
    [bgView addSubview:nameLabel];
    self.nameLabel = nameLabel;
    
    
    //尺寸
    UILabel* sizeLabel = [[UILabel alloc]init];
    sizeLabel.frame = CGRectMake(CGRectGetMinX(nameLabel.frame),CGRectGetMaxY(nameLabel.frame)+5,200, 20);
    sizeLabel.textColor = LZColorFromRGB(132, 132, 132);
    sizeLabel.font = [UIFont systemFontOfSize:14];
    
    [bgView addSubview:sizeLabel];
    self.sizeLabel = sizeLabel;
    
    //选择规格按钮
    UIButton *btnS = [UIButton buttonWithType:(UIButtonTypeCustom)];
    btnS.frame = CGRectMake(CGRectGetMaxX(sizeLabel.frame), CGRectGetMinY(sizeLabel.frame), 20, 20);
    [btnS setImage:[UIImage imageNamed:@"shaixuan_xiajiantou"] forState:(UIControlStateNormal)];
    [btnS setImage:[UIImage imageNamed:@"shaixuan_shangjiantou"] forState:(UIControlStateSelected)];

    [bgView addSubview:btnS];
    self.tempSeBtn = btnS;
    
    
    
    
    
    
    
    
    //价格
    UILabel* priceLabel = [[UILabel alloc]init];
    priceLabel.frame = CGRectMake(CGRectGetMinX(nameLabel.frame), CGRectGetMaxY(imageBgView.frame)-30, 100, 30);
    priceLabel.font = [UIFont boldSystemFontOfSize:16];
    priceLabel.textColor = KQiangGour;
    priceLabel.textAlignment = NSTextAlignmentLeft;
    [bgView addSubview:priceLabel];
    self.priceLabel = priceLabel;
    
   
   
   
    //时间
    UILabel* dateLabel = [[UILabel alloc]init];
    dateLabel.frame = CGRectMake(nameLabel.left, sizeLabel.bottom , 100, 20);
    dateLabel.font = [UIFont systemFontOfSize:10];
    dateLabel.textColor = LZColorFromRGB(132, 132, 132);
    [bgView addSubview:dateLabel];
    self.dateLabel = dateLabel;

    
    
    _tempV = [[UIView alloc] initWithFrame:CGRectMake(bgView.width-130,  CGRectGetMinY(priceLabel.frame), 120, 30)];
    _tempV.backgroundColor = [UIColor whiteColor];
    _tempV.layer.masksToBounds = YES;
    _tempV.layer.cornerRadius = 3;
    _tempV.layer.borderWidth = 1;
    _tempV.layer.borderColor = KShouYeBg.CGColor;
    
    
    [bgView addSubview:_tempV];
    //数量加按钮
    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    addBtn.frame = CGRectMake(_tempV.width - 35, 5, 25, 25);
    [addBtn setImage:[UIImage imageNamed:@"gouwuche_jia"] forState:UIControlStateNormal];
    [addBtn setImage:[UIImage imageNamed:@"gouwuche_jia"] forState:UIControlStateHighlighted];
    [addBtn addTarget:self action:@selector(addBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [_tempV addSubview:addBtn];
    
    //数量显示
    UITextField* numberLabel = [[UITextField alloc]init];
    numberLabel.frame = CGRectMake(addBtn.left - 55, addBtn.top, 50, 25);
    numberLabel.textAlignment = NSTextAlignmentCenter;
    numberLabel.text = @"0";
    
    [numberLabel addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingDidEnd];

    numberLabel.keyboardType =UIKeyboardTypeNumberPad;
    numberLabel.font = [UIFont systemFontOfSize:15];


    [_tempV addSubview:numberLabel];
    self.numberTF = numberLabel;
    
    
    //数量减按钮
    UIButton *cutBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cutBtn.frame = CGRectMake(numberLabel.left - 25, addBtn.top, 25, 25);
    [cutBtn setImage:[UIImage imageNamed:@"gouwuche_jian2"] forState:UIControlStateNormal];
    [cutBtn setImage:[UIImage imageNamed:@"gouwuche_jian2"] forState:UIControlStateHighlighted];
    [cutBtn addTarget:self action:@selector(cutBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [_tempV addSubview:cutBtn];
    
}


//实时监听输入框值的变化
- (void)textFieldEditChanged:(UITextField *)text {
    
    NSInteger count = [text.text integerValue];
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    
 
    if (count < [countMin integerValue]) {
        [MBProgressHUD showText:[NSString stringWithFormat:@"该商品的起定量为%@",countMin]];
        self.numberTF.text = countMin;
        
        count = [countMin integerValue];
      
    }
    
    
    
    
    if ([countMax integerValue] == 0) {//判断该商品是否为限购商品，如果是不是限购，不能大于库存量
        if (count > [countNumT integerValue]) {
            [MBProgressHUD showText:[NSString stringWithFormat:@"该商品的库存仅为%@",countNumT]];
            self.numberTF.text = countNumT;
            count = [countNumT integerValue];
        }
    }
    else {//如果不是限购商品，不能大于限购数量
        if (count > [countMax integerValue]) {

            [MBProgressHUD showText:[NSString stringWithFormat:@"该商品限购订量为%@",countMax]];
            self.numberTF.text = countMax;
            count = [countMax integerValue];

        }
    }
    
    

    NSDictionary *parameDic = @{@"userid":saveDic[@"userid"],@"sku_id":chooseID,@"num":[NSString stringWithFormat:@"%ld",count],@"actoken":[Md5Apiway getMD5data:saveDic[@"userid"]]};
    
    [HttpRequest postWithURLString:POST(Shop_CartUpdateCartNum) parameters:parameDic success:^(id responseObject) {
        if ([responseObject[@"ret"] intValue] != 200) {
            [[DSLHUD shareDSLHUD] showTextNoActivity:@"更改此商品数量出错" timeLength:1.5];
            return ;
        }
        NSLog(@"-=-=-=%@",responseObject);
        NSString *strT = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"code"]];
        if ([strT intValue] != 0) {
            [MBProgressHUD showText:responseObject[@"data"][@"msg"]];
            
        }else {
            
            if (numberCutBlock) {
                numberCutBlock(count);
            }
        }
        
        NSLog(@"修改商品数量返回的结果 ＝＝＝ %@",responseObject);
    } failure:^(NSError *error) {
        
    }];
    
    

    
}


@end
